<template>
<div class="add">
  <el-form :model="ruleForm" @submit.native.prevent :rules="rules" ref="ruleForm" label-width="100px"
           class="demo-ruleForm">
    <el-form-item class="q-row"
                  v-for="(domain, index) in ruleForm.domains"
                  :label="'问题'"
                  :key="domain.key"
                  :prop="'domains.' + index + '.value'"
                  :rules="rules.name"
    >
      <section class="top">
        <!--提示-->
        <el-tooltip placement="bottom" effect="light" popper-class="pop-w" :disabled="checkShow(index)">
          <div slot="content">
            <!--子问题-->
            <el-table
              max-height="500"
              :data="infoData[index]"
              style="width: 100%"
            >
              <el-table-column type="expand">
                <template slot-scope="props">
                  <el-form label-position="left" inline class="demo-table-expand c-tag">
                    <el-form-item label="问题" v-for="(o ,ii) in props.row.s_qstarr" :key="ii" style="width: 100%;">
                      <el-popover trigger="hover" placement="top">
                        <p  style="max-width: 300px">关键词:
                          <el-tag style="margin: 4px" v-for="(n,inde) in o.keywords.split(' ')" :key="inde">
                            {{n.length > 20 ? (n.substring(0,20) + '...') : n}}
                          </el-tag>
                        </p>
                        <div slot="reference" class="name-wrapper">
                <span>
                  {{o.qustion}}
                  <!--{{o.qustion.length > 80 ? (o.qustion.substring(0,80) + '...') : o.qustion}}-->
                </span>
                          <i class="el-icon-question"></i>
                        </div>
                      </el-popover>
                    </el-form-item>
                    <el-form-item label="答案" style="width: 100%;">
            <span>
              {{props.row.s_answer}}
              <!--{{props.row.s_answer.length > 80 ? (props.row.s_answer.substring(0,80) + '...') : props.row.s_answer}}-->
            </span>
                    </el-form-item>
                    <el-form-item label="标签" style="width: 100%">
                      <el-tag style="margin-left: 5px" v-for="tt in props.row.s_tags" :type=" !tt ? 'info' : ''" :key="tt">{{tt ? tt : '无标签'}}</el-tag>
                    </el-form-item>
                    <el-form-item label="关键词" style="width: 100%;">
                      <el-tag type="success" style="margin-left: 5px" v-for="tt in props.row.s_keywords.split(',')" :key="tt">
                        {{tt.length > 20 ? (tt.substring(0,20) + '...') : tt}}
                      </el-tag>
                    </el-form-item>
                    <el-form-item label="ID">
                      <span>{{ props.row._id }}</span>
                    </el-form-item>
                    <el-form-item label="父级 ID">
                      <el-tag type="warning" v-for="tt in props.row.s_pids" :key="tt" v-if="tt">
                        {{tt}}
                      </el-tag>
                    </el-form-item>
                  </el-form>
                </template>
              </el-table-column>
              <el-table-column
                label="问题"
                width="200"
              >
                <template slot-scope="scope">
                  <div class="drop-text">
                    {{scope.row.s_qstarr[0].qustion}}
                    <!--{{scope.row.s_qstarr[0].qustion.length > 30 ? (scope.row.s_qstarr[0].qustion.substring(0,30) + '...') : scope.row.s_qstarr[0].qustion}}-->
                  </div>
                </template>
              </el-table-column>
              <el-table-column
                label="答案"
                width="200"
              >
                <template slot-scope="scope">
                  <div class="drop-text">
                    {{scope.row.s_answer}}
                    <!--{{scope.row.s_answer.length > 30 ? (scope.row.s_answer.substring(0,30) + '...') : scope.row.s_answer}}-->
                  </div>
                </template>
              </el-table-column>
              <el-table-column
                label="标签"
                width="200"
                prop="s_tags"
              >
                <template slot-scope="scope">
                  <section>
                    <el-tag v-for="t in scope.row.s_tags.slice(0,2)" :key="t" style="margin: 4px 10px 4px 0;" :type=" !t ? 'info' : ''">
                      {{t ? t : '无标签'}}
                    </el-tag>
                  </section>
                </template>
              </el-table-column>
              <el-table-column
                label="关键字"
                width="200"
                prop="s_keywords">
                <template slot-scope="scope">
                  <section>
                    <el-tag v-for="t in scope.row.s_keywords.split(',').slice(0,2)" :key="t" style="margin: 4px 10px 4px 0;" type="success">
                      {{t.length > 8 ? (t.substring(0,8) + '...') : t}}
                    </el-tag>
                  </section>
                </template>
              </el-table-column>
              <el-table-column
                label="操作"
                fixed="right"
                width="80"
              >
                <template slot-scope="scope">
                  <el-button
                    v-if="$route.params.pid && !ruleForm.status"
                    size="mini"
                    type="warning"
                    @click="untieRow(scope.$index, scope.row)">引用
                  </el-button>
                  <el-button
                    v-else
                    size="mini"
                    type="warning"
                    @click="editRow(scope.$index, scope.row)">编辑
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
            <!--子问题-->
          </div>
          <el-input v-model="domain.value" type="textarea" :autosize="{ minRows: 1.4, maxRows: 5}"
                    placeholder="请输入问题描述" @input="changeText(index,domain.value)"></el-input>
        </el-tooltip>
        <!--<el-autocomplete v-model="domain.value" type="textarea" :autosize="{ minRows: 1, maxRows: 4}"-->
        <!--placeholder="请输入问题描述" :fetch-suggestions="querySearchAsync" :trigger-on-focus="false" @select="handleSelect"></el-autocomplete>-->
        <!--删除-->
        <el-button v-if="index !== 0" class="del" type="danger" @click.prevent="removeDomain(domain)"
                   icon="el-icon-delete"></el-button>
        <el-form-item v-else class="left" style="margin-left: 6px">
          <el-button @click="addDomain" icon="el-icon-circle-plus" type="primary" plain>新增问题</el-button>
        </el-form-item>
      </section>
      <section class="b-row">
        <el-tag
          type="success"
          :key="ii"
          v-for="(tag,ii) in domain.dynamicTags"
          :closable="true"
          :disable-transitions="false"
          :rules="rules.name"
          @close="handleClose(tag,index)"
          @click.native="showText(index,tag)"
        >
          {{tag.length > 20 ? (tag.substring(0,20) + '...') : tag}}
        </el-tag>
        <el-input
          class="input-new-tag"
          v-if="domain.inputVisible"
          v-model="domain.inputValue"
          ref="saveTagInput"
          size="small"
          @keyup.enter.native="handleInputConfirm(index)"
          @blur="handleInputConfirm(index)"
        >
        </el-input>
        <el-button v-else class="button-new-tag" type="primary" @click="showInput(index)"
                   icon="el-icon-plus"></el-button>
      </section>
    </el-form-item>
    <el-form-item label="答案" prop="a">
      <el-input type="textarea" :autosize="{ minRows: 2, maxRows: 5}" placeholder="请输入对应答案"
                v-model="ruleForm.a"></el-input>
    </el-form-item>
    <el-form-item label="选择标签" class="left" :rules="rules.name">
      <section class="select">
        <el-tag v-for="t in ruleForm.allTag" :key="t" @click.native="addTag(t)" :type="ruleForm.tags.includes(t) ? 'success' : 'info'">
          {{t}}
        </el-tag>
      </section>
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="submitForm('ruleForm')">{{ruleForm.status ? '更新' : '立即保存'}}</el-button>
      <el-button @click="resetForm('ruleForm')" v-if="!ruleForm.status">清空</el-button>
      <el-button @click="delThis" type="danger" v-else>删除</el-button>
    </el-form-item>
  </el-form>
</div>
</template>
<script>
import ElFormItem from 'element-ui/packages/form/src/form-item'
import { saveQa, getInfo, unQa, delQa, getTag } from '../api/getData'

export default {
  components: {ElFormItem},
  name: 'add',
  data: function () {
    return {
      timing: {
        old: 0,
        tt: '',
        step: 1,
        min: 4
      },
      infoData: [],
      subData: {
        usercode: '',
        tag: '',
        qstarr: '',
        keywords: '',
        answer: '',
        pid: '', // 关联父级id
        flagTag: '', // 更新标识
        _id: '', // 修改数据的id
        state: '3' // 状态标识
      },
      ruleForm: {
        tempTag: [],
        status: false,
        uid: window.localStorage.getItem('uid') || '默认001',
        a: '',
        allTag: ['工商', '剑鱼'],
        tags: [],
        domains: [{
          value: '',
          dynamicTags: [],
          inputVisible: false,
          inputValue: ''
        }]
      },
      rules: {
        name: [
          {required: true, message: '请输入问题描述', trigger: 'blur'},
          {min: 2, message: '长度最小需要2个字符', trigger: 'blur'}
        ],
        a: [
          {required: true, message: '请输入对应答案', trigger: 'blur'},
          {min: 1, message: '长度最小需要1个字符', trigger: 'blur'}
        ]
      }
    }
  },
  created: function () {}, // 创建时
  beforeMount: function () {}, // 挂载之前
  mounted: function () {
    this.$bus.$on('addData', data => {
      this.setAdd(data)
    })
    this.getTags()
  }, // 挂载之后
  beforeUpdate: function () {}, // 数据更新时调用,在渲染之前
  updated: function () {}, // 数据更新后,渲染后调用(禁止)
  beforeDestroy: function () {}, // 实例销毁前调用,解绑中间层的数据传输
  destroyed: function () {}, // 实例销毁后调用
  methods: {
    /* 获取标签 */
    getTags () {
      return getTag().then(({data}) => {
        let flag = data.msg === 'success'
        if (flag) {
          this.$notify({
            title: '获取标签失败',
            position: 'top-right',
            message: '获取标签失败，请刷新',
            type: 'error'
          })
        } else {
          this.ruleForm.allTag = data
        }
      }).catch(err => {
        this.$notify({
          title: '获取标签失败',
          position: 'top-right',
          message: err,
          type: 'error'
        })
      })
    },
    /* 判断为空不显示提示 */
    checkShow (i) {
      return !(Array.isArray(this.infoData[i]) ? this.infoData[i].length : false)
    },
    changeText (index, str) {
      if (str.trim().length === 0) {
        this.ruleForm.domains[index].dynamicTags = []
        this.ruleForm.tempTag = []
        this.infoData.splice(index, 1, [])
      }
      if (str.length < this.timing.min) { return false }
      let now = new Date().getTime() / 1000
      let old = this.timing.old || now
      if (now - old < this.timing.step) {
        clearTimeout(this.timing.tt)
      }
      this.timing.old = now
      this.timing.tt = setTimeout(() => {
        let id = ''
        if (this.ruleForm.status) {
          id = this.$route.params.sid || ''
        } else {
          id = this.$route.params.pid || ''
        }
        getInfo({question: str, id}).then(({data}) => {
          let tempTag = data[0] ? data[0].split(' ') : []
          if (this.ruleForm.tempTag.length !== 0) {
            /* 删除之前生成的提示 */
            let tempArr = this.ruleForm.domains[index].dynamicTags.filter(v => !this.ruleForm.tempTag.includes(v))
            this.ruleForm.domains[index].dynamicTags = tempArr
          }
          /* 添加生成的提示 */
          this.ruleForm.tempTag = tempTag
          let tempArr = [...this.ruleForm.tempTag, ...this.ruleForm.domains[index].dynamicTags]
          this.ruleForm.domains[index].dynamicTags = Array.from(new Set(tempArr))
          /* 更新提示列表 */
          this.infoData.splice(index, 1, data[1])
        }).catch(err => {
          console.log('--err--', err)
        })
      }, this.timing.step * 1000)
    },
    untieRow (index, row) {
      unQa({
        id: row._id,
        pid: this.$route.params.pid,
        flagState: 'A'
      }).then(({data}) => {
        let flag = data.msg === 'success'
        this.$notify({
          title: flag ? '绑定成功' : '绑定失败',
          position: 'top-right',
          message: flag ? '已成功绑定关系' : data.msg,
          type: flag ? 'success' : 'error'
        })
        if (flag) {
          setTimeout(() => {
            this.$router.back()
          }, 1500)
        }
      }).catch(err => {
        this.$notify({
          title: '绑定失败',
          position: 'top-right',
          message: err,
          type: 'error'
        })
      })
    },
    editRow (index, row) {
      this.$router.push('/amend/' + row._id)
    },
    delThis () {
      delQa({id: this.$route.params.sid}).then(({data}) => {
        let flag = data.msg === 'success'
        this.$notify({
          title: flag ? '删除成功' : '删除失败',
          position: 'top-right',
          message: flag ? '已成功删除问答' : data.msg,
          type: flag ? 'success' : 'error'
        })
        if (flag) {
          return this.$router.back()
        }
      }).catch(err => {
        this.$notify({
          title: '删除失败',
          position: 'top-right',
          message: err,
          type: 'error'
        })
      })
    },
    getSubData () {
      this.subData.usercode = this.ruleForm.uid
      this.subData.answer = this.ruleForm.a
      this.subData.tag = this.ruleForm.tags.join(',')
      let tempArr = []
      let obj = {}
      this.ruleForm.domains.forEach(v => {
        obj[v.value] = v.dynamicTags.join(' ')
        v.dynamicTags.forEach(s => {
          if (!tempArr.includes(s)) {
            tempArr.push(s)
          }
        })
      })
      this.subData.qstarr = JSON.stringify(obj)
      this.subData.keywords = tempArr.join(',')
      this.subData.pid = this.$route.params.pid || ''
      this.subData.flagTag = this.$route.params.sid ? 'U' : ''
      this.subData._id = this.$route.params.sid || ''
    },
    /* 提交 */
    submitForm (formName) {
      /* 判断问题 */
      if (!this.ruleForm.domains.length) {
        this.$notify({
          title: '添加失败',
          position: 'top-right',
          message: '您当前还没有问题,请添加问题',
          type: 'warning'
        })
        return false
      }
      /* 判断关键字 */
      let f = this.ruleForm.domains.every(v => v.dynamicTags.length)
      if (!f) {
        this.$notify({
          title: '添加失败',
          position: 'top-right',
          message: '请检查关键字是否输入,不存在请点击问题下发的+号手动添加',
          type: 'warning'
        })
        return false
      }
      if (this.ruleForm.tags.length === 0) {
        this.$notify({
          title: '添加失败',
          position: 'top-right',
          message: '必须添加至少一个标签',
          type: 'warning'
        })
        return false
      }
      /* 判断必填项 */
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.getSubData()
          /* ajax */
          saveQa(this.subData).then(({data}) => {
            if (data.msg === 'success') {
              this.$notify({
                title: this.subData.flagTag === 'U' ? '更新成功' : '添加成功',
                position: 'top-right',
                message: this.subData.flagTag === 'U' ? '问答信息更新成功' : '问答信息添加成功',
                type: 'success'
              })
              return this.subData.flagTag === 'U' ? true : this.resetForm('ruleForm')
            } else {
              this.$notify({
                title: '添加失败',
                position: 'top-right',
                message: data.msg,
                type: 'error'
              })
            }
          }).catch(err => {
            this.$notify({
              title: '添加失败',
              position: 'top-right',
              message: err,
              type: 'error'
            })
          })
        } else {
          this.$notify({
            title: '添加失败',
            position: 'top-right',
            message: '请检查您是否填写所有带 * 必填项',
            type: 'warning'
          })
          return false
        }
      })
    },
    resetForm (formName) {
      this.infoData = []
      this.$refs[formName].resetFields()
      this.ruleForm.tags = []
      this.ruleForm.domains = [{
        value: '',
        dynamicTags: [],
        inputVisible: false,
        inputValue: ''
      }]
    },
    /* 问题 */
    addDomain () {
      this.ruleForm.domains.push({
        value: '',
        dynamicTags: [],
        inputVisible: false,
        inputValue: '',
        key: Date.now()
      })
    },
    removeDomain (item) {
      var index = this.ruleForm.domains.indexOf(item)
      if (index !== -1) {
        this.ruleForm.domains.splice(index, 1)
        this.infoData.splice(index, 1, [])
      }
    },
    /* 关键词 */
    handleClose (tag, index) {
      this.ruleForm.domains[index].dynamicTags.splice(this.ruleForm.domains[index].dynamicTags.indexOf(tag), 1)
    },
    showInput (index) {
      this.ruleForm.domains[index].inputVisible = true
      this.$nextTick(() => {
        this.$refs.saveTagInput[0].$refs.input.focus()
      })
    },
    showText (i, tag) {
      this.showInput(i)
      this.ruleForm.domains[i].inputValue = tag
      this.handleClose(tag, i)
    },
    handleInputConfirm (index) {
      let inputValue = this.ruleForm.domains[index].inputValue
      if (inputValue) {
        this.ruleForm.domains[index].dynamicTags.push(inputValue)
      }
      this.ruleForm.domains[index].inputVisible = false
      this.ruleForm.domains[index].inputValue = ''
    },
    /* 标签 */
    tagClose (tag) {
      this.ruleForm.tags.splice(this.ruleForm.tags.indexOf(tag), 1)
    },
    addTag (tag) {
      if (this.ruleForm.tags.indexOf(tag) === -1) {
        this.ruleForm.tags.push(tag)
      } else {
        this.ruleForm.tags.splice(this.ruleForm.tags.indexOf(tag), 1)
      }
    },
    /* 放入数据 */
    setAdd (data) {
      this.ruleForm.status = true
      this.$route.params.pid = data.s_pids.join(',')
      this.$route.params.sid = data._id
      this.ruleForm.tags = data.s_tags
      this.ruleForm.a = data.s_answer
      this.ruleForm.uid = data.s_usercode
      this.ruleForm.domains = data.s_qstarr.map(v => {
        let obj = {
          value: v.qustion,
          dynamicTags: v.keywords.split(' '),
          inputVisible: false,
          inputValue: ''
        }
        return obj
      })
    }
  } // 函数
}
</script>
<style lang='scss'>
.add {
  box-sizing: border-box;
  .pop-w {

  }
  textarea {
    font-family: "Helvetica Neue", Helvetica, "PingFang SC", "Hiragino Sans GB", "Microsoft YaHei", "微软雅黑", Arial, sans-serif;
  }
  .select {
    border: 3px dashed #DCDFE6;
    padding: 15px;
  }
  .tip {
    color: #909399;
  }
  .left {
    text-align: left;
  }
  .q-row {

    .top {
      display: flex;
      flex-direction: row;
    }
    .b-row {
      margin-left: 34px;
      text-align: left;
      margin-top: 20px;
    }
    .del {
      padding: 0px 10px;
      margin-left: 6px;
      font-size: 16px;
    }
  }
  .el-tag {
    margin-left: 10px;
    cursor: pointer;
  }
  .el-tag + .el-tag {
    /*margin-left: 10px;*/
  }
  .button-new-tag {
    margin-left: 10px;
    height: 32px;
    line-height: 30px;
    padding-top: 0;
    padding-bottom: 0;
  }
  .input-new-tag {
    width: 90px;
    margin-left: 10px;
    vertical-align: bottom;
  }
}
.drop-text {
  width: 200px;
  overflow: hidden;
  text-overflow:ellipsis;
  white-space:nowrap;
  text-align: left;
}
.c-tag {
  display: flex;
  flex-direction: column;
  align-items: flex-start;
  .el-form-item{
    display: flex;
    flex-direction: row;
    align-items: flex-start;
    .el-form-item__label{
      max-width: 5rem;
      min-width: 5rem;
    }
  }
}
</style>
